/*
 * @Author: Wilbur
 * @Date: 2019-08-12 14:08:39
 * @Last Modified by: Wilbur
 * @Last Modified time: 2019-08-28 12:00:19
 */

<template>
    <div class="container goods-list-container">
        <div class="operation-wrapper">
            <div class="select-container">
                选择分类：
                <el-select
                    class="filter-input"
                    v-model="filterData.parent_type_no"
                    size="medium"
                    @change="getTableData(1)"
                    placeholder="请选择"
                    style="width: 300px !important"
                >
                    <el-option
                        v-for="(item) in selectList"
                        :key="item.no"
                        :label="item.title"
                        :value="item.no"/>
                </el-select>
            </div>
            <el-button
                type="primary"
                @click="fnAddClick"
                size="small">添加分类</el-button>
        </div>
        <div class="content-wrapper">
            <div class="table-wrapper">
                <el-table
                    :data="tableData"
                    height="100%"
                    style="width: 100%;">
                    <el-table-column
                        fixed="left"
                        header-align="left"
                        align="center"
                        :width="50"
                        label="序号">
                        <template slot-scope="scope">
                            <div class="table-index">
                                {{ scope.$index + 1 }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        fixed="left"
                        prop="type_name"
                        show-overflow-tooltip
                        label="主分类"/>
                    <el-table-column
                        prop="sub_type_name"
                        :formatter="emptyFormatter"
                        show-overflow-tooltip
                        label="子分类"/>
                    <el-table-column
                        prop="type_status"
                        show-overflow-tooltip
                        label="子分类logo">
                        <template slot-scope="scope">
                            <template v-if="scope.row.sub_type_logo == ''">--</template>
                            <template v-if="scope.row.sub_type_logo != ''">
                                <img
                                    class="sub-logo"
                                    :src="scope.row.sub_type_logo"
                                    alt="">
                            </template>

                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="type_sort"
                        label="排序"
                    >
                        <template slot-scope="scope">
                            <div class="sort-wrap">
                                {{ scope.row.type_sort }}
                                <span class="sort-spliter" />
                                <el-button
                                    type="text"
                                    class="btn-sort"
                                    style="color: #606266"
                                    @click="fnEditSort(scope.row)"
                                >
                                    <i class="el-icon-edit" />
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="goods_num"
                        show-overflow-tooltip
                        label="商品数量">
                        <template slot-scope="scope">
                            <span v-if="scope.row.sub_type_no == ''">{{ scope.row.goods_num }}</span>
                            <span
                                v-if="scope.row.sub_type_no !== ''"
                                :class="scope.row.goods_num == 0 ? 'num-active' : ''"
                            >{{ scope.row.goods_num }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="type_status"
                        show-overflow-tooltip
                        label="状态">
                        <template slot-scope="scope">
                            <template v-if="scope.row.type_status == 1">已启用</template>
                            <template v-if="scope.row.type_status == 0">已隐藏</template>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="type_status"
                        show-overflow-tooltip
                        label="商品">
                        <template slot-scope="scope">
                            <el-button
                                type="text"
                                @click="handleRoute('GoodsList', {type_no: scope.row.type_no, sub_type_no: scope.row.sub_type_no})">查看商品</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="date"
                        label="操作"
                        :width="140"
                        fixed="right">
                        <template slot-scope="scope">
                            <div>
                                <el-button
                                    type="text"
                                    @click="fnEditClassify(scope.row)">编辑</el-button>
                                <el-button
                                    type="text"
                                    @click="fnChangeClassifyStatus(scope.row)">
                                    <span v-if="scope.row.type_status == 0">启用</span>
                                    <span v-if="scope.row.type_status == 1">隐藏</span>
                                </el-button>
                                <el-button
                                    type="text"
                                    style="margin-left:10px;"
                                    :disabled="scope.row.can_delete == 1 ? false : true"
                                    @click="fnDelMaterial(scope.row)">
                                    删除
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- <div class="pagination-wrapper clearfix">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :total="page.total_count"
                    :page-size="page.page_size"
                    @current-change="getTableData" />
            </div> -->
        </div>
        <!-- 添加课程分类弹窗 -->
        <el-dialog
            title="分类"
            width="475px"
            :visible.sync="dialogAddVisible">
            <el-form
                :model="ruleForm"
                :rules="rules"
                ref="ruleForm"
                label-width="80px"
                class="demo-ruleForm">
                <el-form-item
                    label="课程分类"
                    prop="type">
                    <el-radio-group
                        v-model="ruleForm.type"
                        :disabled="typeDisabled"
                        @change="fnTypeChange">
                        <el-radio label="1">
                            主分类
                        </el-radio>
                        <el-radio label="2">
                            子分类
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item
                    v-if="ruleForm.type == '2'"
                    label="主分类"
                    prop="parent_type_no">
                    <el-select
                        v-model="ruleForm.parent_type_no"
                        class="add-dialog-input"
                        placeholder="请选择主分类">
                        <el-option
                            v-for="(item, index) in typeList"
                            :key="index"
                            :label="item.title"
                            :value="item.no"/>
                    </el-select>
                </el-form-item>
                <el-form-item
                    label="分类名称"
                    prop="type_name">
                    <el-input
                        v-model="ruleForm.type_name"
                        class="add-dialog-input"/>
                </el-form-item>

                <el-form-item
                    v-if="ruleForm.type == '2'"
                    label="分类Logo"
                    prop="type_logo">
                    <el-upload
                        :show-file-list="false"
                        :http-request="e=> {fnUploadImageOfGoods(e)}"
                        accept="image/*"
                        class="upload-good-image"
                        action="https://jsonplaceholder.typicode.com/posts/">
                        <img
                            v-if="ruleForm.type_logo"
                            :src="ruleForm.type_logo"
                            class="avatar">
                        <i
                            v-else
                            class="el-icon-plus avatar-uploader-icon"/>
                    </el-upload>
                </el-form-item>

                <el-form-item
                    label="排序号"
                    prop="type_sort">
                    <el-input
                        v-model="ruleForm.type_sort"
                        type="number"
                        class="add-dialog-input"/>
                </el-form-item>
            </el-form>
            <div
                slot="footer"
                class="dialog-footer">
                <el-button @click="dialogAddVisible = false">取 消</el-button>
                <el-button
                    type="primary"
                    @click="submitForm('ruleForm')">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        var checkTypeLogo = (rule, value, callback) => {
            if (this.ruleForm.type_logo == '') {
                return callback(new Error('请上传分类图片'));
            }else{
                callback();
            }
        };
        var validateName = (rule, value, callback) => {
            if (value.indexOf('首页') != -1) {
                callback(new Error('错误内容，请不要包含”首页“关键词'));
            } else {
                callback();
            }
        };

        return {
            authResult: {},
            tableData: [],
            filterData: {
                parent_type_no: ''
            },
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 0
            },
            baseUrl: '',
            mobileUrl: '',
            escape: escape,
            sessionTicket: localStorage.getItem('sessionTicket'),
            dialogAddVisible: false,
            typeList: [],
            selectList: [],
            ruleForm: {
                type_name: '',
                type: '1',
                type_sort: '',
                parent_type_no: '',
                type_no: '',
                type_logo: ''
            },
            typeDisabled: false,
            rules: {
                type_name: [
                    { required: true, message: '请输入分类名称', trigger: 'blur' },
                    { validator: validateName, trigger: 'blur' }
                ],
                type_sort: [
                    { required: true, message: '请输入排序编号', trigger: 'blur' }
                ],
                type: [
                    { required: true, message: '请选择课程分类', trigger: 'change' }
                ],
                parent_type_no: [
                    { required: true, message: '请选择主分类', trigger: 'change' }
                ],
                type_logo: [
                    {validator: checkTypeLogo, trigger: 'blur'}
                ]
            }
        };
    },
    created() {
        this.authResult = this.$route.meta.authResult;
        this.baseUrl = this.$baseUrl;
        this.mobileUrl = location.host == 'phaadmin.wxhand.com' ? 'http://class.zsdx.cn' : 'http://task.wxhand.com';
        this.$store.commit('SET_HEADER', [
            {
                title: "APP后台",
            },
            {
                title: '商城'
            },
            {
                title: '商品分类'
            }
        ]);
        this.fnGetTypeList();
    },
    mounted() {
        this.getTableData();
    },
    methods: {
        fnEditSort(item) {
            this.$prompt('修改排序', '', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /^(0|\+?[1-9][0-9]*)$/,
                inputPlaceholder: '请输入序号',
                inputErrorMessage: '请输入正整数',
                closeOnClickModal: false,
            }).then(({ value }) => {

                this.$post('/student/shop_goods_type%5Cmodify', {
                    type_no: item.sub_type_no == '' ? item.type_no : item.sub_type_no,
                    type_sort: value
                }, resp => {
                    if (resp.code == 1) {
                        this.$set(item, 'type_sort', value);
                        this.getTableData();
                        this.$message({
                            type: 'success',
                            message: '操作成功',
                            center: true
                        });
                    }
                });
            }).catch(() => {
            });
        },
        fnUploadImageOfGoods(e) {
            this.fnUploadImage(e, (resp) => {
                this.ruleForm.type_logo = resp.data.url;
            }, (resp) => {
                console.log(resp.msg);
            });
        },
        fnUploadImage(e, success, error) {
            let timeTmp = new Date().getTime();
            let pic = new FormData();

            pic.append('file', e.file);
            this.$upload({
                url: '/__local/common%5Cupload',
                data: pic,
                success: resp => {
                    if (resp.code == 1) {
                        success(resp);
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                        error(resp);
                    }
                }
            });
        },
        fnAddClick() {
            this.ruleForm = {
                type_name: '',
                type: '1',
                type_sort: '',
                parent_type_no: '',
                type_no: '',
                type_logo: ''
            };
            this.typeDisabled = false;
            this.dialogAddVisible = true;
        },
        fnEditClassify(row) {
            let no = '';

            if(row.sub_type_no == '') {
                no = row.type_no;
            }else{
                no = row.sub_type_no;
            }

            this.$post('/student/shop_goods_type%5Cget', {
                type_no: no
            }, resp => {
                if (resp.code == 1) {
                    this.typeDisabled = true;
                    this.ruleForm.type_name = resp.data.type_name;
                    if(resp.data.parent_type_no == '') {
                        this.ruleForm.type = '1';
                    }else{
                        this.ruleForm.type = '2';
                    }
                    this.ruleForm.type_sort = resp.data.type_sort;
                    this.ruleForm.parent_type_no = resp.data.parent_type_no;
                    this.ruleForm.type_no = resp.data.type_no;
                    this.ruleForm.type_logo = resp.data.type_logo;

                    this.dialogAddVisible = true;

                }
            });
        },
        fnTypeChange(){
            if(this.ruleForm.type == '2' && this.typeList.length == 0) {
                this.fnGetTypeList();
            }
        },
        fnGetTypeList() {
            this.$post('/student/shop_goods_type%5Cget_list_linkage', {}, resp => {
                if (resp.code == 1) {
                    this.typeList = resp.data.list;
                    this.selectList = resp.data.list;
                }
            });
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let data = {};

                    data.parent_type_no = this.ruleForm.parent_type_no;
                    data.type_no = this.ruleForm.type_no;
                    data.type_name = this.ruleForm.type_name;
                    data.type_sort = this.ruleForm.type_sort;
                    data.type_logo = this.ruleForm.type_logo;
                    this.fnSetData(data);
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        fnSetData(data) {
            this.$post('/student/shop_goods_type%5Csave', data, resp => {
                if (resp.code == 1) {
                    this.getTableData();
                    this.fnGetTypeList();
                    this.$message({
                        type: 'success',
                        message: '操作成功',
                        center: true
                    });
                    this.resetForm('ruleForm');
                    this.dialogAddVisible = false;
                }else{
                    this.$message({
                        type: 'warning',
                        message: resp.msg,
                        center: true
                    });
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        fnAddClassify() {

        },
        fnChangeClassifyStatus(row) {
            let status = row.type_status == 1 ? 0 : 1;

            this.$post('/student/shop_goods_type%5Cmodify', {
                type_no: row.sub_type_no == '' ? row.type_no : row.sub_type_no,
                type_status: status
            }, resp => {
                if (resp.code == 1) {
                    this.$set(row, 'type_status', status);
                    this.$message({
                        type: 'success',
                        message: '操作成功',
                        center: true
                    });
                }
            });
        },
        fnDelMaterial(row) {
            this.$confirm('删除该分类, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$post('/student/shop_goods_type%5Cdelete', {
                    type_no: row.sub_type_no == '' ? row.type_no : row.sub_type_no
                }, resp => {
                    if (resp.code == 1) {
                        this.getTableData(this.page.now_page);
                        if(row.sub_type_no == '') {
                            this.fnGetTypeList();
                        }
                        this.$message({
                            type: 'success',
                            message: '操作成功',
                            center: true
                        });
                    } else if (resp.code == 0) {
                        this.$message({
                            type: 'warning',
                            message: resp.msg
                        });
                    }
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        fnComputedTags(array) {
            let temp = '';

            for(let i = 0; i < array.length; i++) {
                if(temp) {
                    temp += ',';
                }
                temp += array[i].tag_name;
            }
            return temp;
        },
        fnAddTag() {
            this.$prompt('请输入新增标签名称', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /\S/,
                inputErrorMessage: '请输入标签名称'
            }).then(({ value }) => {
                this.$message({
                    type: 'success',
                    message: '操作成功',
                    center: true
                });
            }).catch(() => {
            });
        },
        fnChangeBidStatus(id, status) {
            this.$post('/wei4/base%5Cbanner%5Cset_status', {
                id: id,
                status: status == 1 ? 0 : 1
            }, resp => {
                if (resp.code == 1) {
                    this.getTableData(this.page.now_page);
                    this.$message({
                        type: 'success',
                        message: '操作成功',
                        center: true
                    });
                }
            });
        },
        /**
         * 获取表格数据
         */
        getTableData(page) {

            this.$post('/student/shop_goods_type%5Cget_list', {
                page: page || this.page.now_page,
                type_no: this.filterData.parent_type_no
            }, resp => {
                if (resp.code == 1) {
                    this.tableData = resp.data.list;
                    // this.page.now_page = resp.data.page.now_page;
                    // this.page.total_count = resp.data.page.total_count;
                    // this.page.page_size = resp.data.page.page_size;
                }
            });
        },

        /**
         * 跳转页面
         */
        handleRoute(name, query) {
            let obj = {
                name
            };

            if (query) {
                obj.query = query;
            }

            this.$router.push(obj);
        },

        /**
         * 列表渲染辅助函数：列表项为空处理
         */
        emptyFormatter(row, column, val) {
            if (!val) {
                return '--';
            }
            return val;
        }
    }
};
</script>

<style lang="less" scoped>
.container {
    display: flex;
    flex-direction: column;
    width: 100%;
}
.add-dialog-input{
    width: 350px;
}
.operation-wrapper {
    display: flex;
    padding: 12px 23px;
    background-color: #fff;
    .select-container{
        flex: 1;
    }
    .el-button {
        float: right;
        margin-left: 10px;
    }
}
.content-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin: 15px;
    overflow: hidden;
}
.search-wrapper {
    padding: 15px;
    background-color: #fff;
}
.filter-item {
    .el-form-item {
        margin-bottom: 0;
        white-space: nowrap;
    }
    .el-input {
        width: auto;
        vertical-align: middle;
    }
    .el-button {
        margin-left: 15px;
        vertical-align: middle;
    }
}
.table-wrapper {
    flex: 1;
    background-color: #fff;
    .sub-logo{
        width: 50px;
        height: 50px;
    }
    .num-active {
        color: #FF0000;
    }
}
.pagination-wrapper {
    padding-top: 10px;
    .el-pagination {
        float: right;
        padding: 0;
        background-color: transparent;
    }
}
</style>
<style lang="less">
.goods-list-container {
    tbody {
        .cell {
            display: flex;
            align-items: center;
            height: 48px;
        }
    }
    .upload-good-image{
        border: 1px solid red;
        width: 100px;
        height: 100px;
        display: flex;
        border: 1px dashed #d9d9d9;
        border-radius: 4px;
        align-items: center;
        justify-content: center;
        font-size: 34px;
        color: #8c939d;
        img{
            width: 100px;
            height: 100px;
        }
    }
}
</style>
